package com.fingard.dsp.bank.dbobj.updownfile;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.dbobj.unique.UniqueIdHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.InsertHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.LoadHelper;
import com.fingard.text.StringHelper;

/**文件下载记录操作类*/
public class DownFileHelper {
	private Connection partDbconn = null;
	
	/**！！注意：需在finally里显示调用close()方法
	 * @param 租户
	 * @param 日期*/
	public DownFileHelper(String pTenant, Date pPartDate) throws Exception{
		partDbconn = FGBiz.partTable.getLoaclDbConnByPart(pTenant, pPartDate);
	}
	
	public void close(){
		if(partDbconn != null){
			try{
				partDbconn.close();
			}catch(Exception ex){
				FGBiz.limitMsg.exception("ReceiptDataHelper.closeLocalDbConn", ex);
			}
		}
	}
	
	private String getTableName(){
		return "DOWNFILE";
	}
	
	/**将回单数据写入数据库表*/
	public int insertIfNotExist(DownFileRecord pData) throws Exception{
		String tabName = getTableName();//FILEPATH, BUSDATE, OWNACT, SRCSYS
		String chkSql = "select count(*) from "+tabName+" where FILEPATH=? and BUSDATE=? and OWNACT=? and SRCSYS=?";
		Object[] objs = new Object[4];
		objs[0] = pData.filePath;
		objs[1] = pData.busDate;
		objs[2] = pData.ownAct;
		objs[3] = pData.srcSys;
		Object chkObj = JDBCHelper.execScalar(partDbconn, chkSql, objs);
		int chkCount = 0;
		if(chkObj != null){
			chkCount = Integer.parseInt(chkObj.toString());
		}
		if(chkCount <= 0){
			pData.urid = UniqueIdHelper.getUniqueId("DOWNFILE");
			pData.createdOn = new Date();
			pData.lastModifiedOn = new Date();
			pData.rowVersion = 1;
			int rowAff = InsertHelper.insertObject(partDbconn, tabName, pData);
			if(rowAff == 1){
				return 1;
			}else{
				throw new Exception("写入"+tabName+"的影响行数："+rowAff);
			}
		}else{
			return 0;
		}
	}
	
	/**根据urid查询DownFileRecord*/
	public DownFileRecord loadFromDbByUrid(long pUrid) throws SQLException, IllegalArgumentException, IllegalAccessException, ParseException{
		String tabName = getTableName();
		String sql = "select * from "+tabName+" where URID=?";
		Object[] objs = new Object[1];
		objs[0] = pUrid;
		return loadOneDataBySql(sql, objs);
	}
	
	/**根据文件名查询DownFileRecord*/
	public DownFileRecord loadFromDbByFilePath(String pFilePath, int pBusDate, String pOwnAct, String pSrcSys) throws SQLException, IllegalArgumentException, IllegalAccessException, ParseException{
		String tabName = getTableName();
		String sql = "select * from "+tabName+" where FILEPATH=? and BUSDATE=? and OWNACT=? and SRCSYS=?";
		Object[] objs = new Object[4];
		objs[0] = pFilePath;
		objs[1] = pBusDate;
		objs[2] = pOwnAct;
		objs[3] = pSrcSys;
		return loadOneDataBySql(sql, objs);
	}
	
	/**根据sql语句查询一条记录，载入DownFileRecord对象返回*/
	private DownFileRecord loadOneDataBySql(String pSql, Object[] pObjPms) throws SQLException, IllegalArgumentException, IllegalAccessException, ParseException{
		Map<String,Object> mapData = JDBCHelper.execQuerySingle(partDbconn, pSql, pObjPms);
		if(mapData != null && mapData.size() > 0){
			DownFileRecord respData = new DownFileRecord();
			LoadHelper.loadObject(mapData, respData);
			return respData;
		}
		return null;
	}
	
	
	/**获取需要下载的URID列表，DOWNSTATE in('1','3')*/
	public HashMap<Long, Integer> getNeedDownList(Date pDate, String pSrcSys, String pBankFrontCode) throws SQLException{
		String tabName = getTableName();
		int busDate = Integer.parseInt(Format.Date8Format.format(pDate));
		String sql = "select URID,ROWVERSION from "+tabName+" where BUSDATE=? and DOWNSTATE in('1','3') and SRCSYS=? and BANKFRONTCODE=?";
		Object[] objs = new Object[3];
		objs[0] = busDate;
		objs[1] = pSrcSys;
		objs[2] = pBankFrontCode;
		return getUridListBySql(sql, objs);
	}
	
	/**获取当前前置机当前分区表所有需要下载的文件URID列表，DOWNSTATE in('1','3')
	 * @throws SQLException */
	public HashMap<Long, Integer> getAllNeedDownList(String pSrcSys, String pBankFrontCode) throws SQLException{
		String tabName = getTableName();
		String sql = "select URID,ROWVERSION from "+tabName+" where DOWNSTATE in('1','3') and SRCSYS=? and BANKFRONTCODE=?";
		Object[] objs = new Object[2];
		objs[0] = pSrcSys;
		objs[1] = pBankFrontCode;
		return getUridListBySql(sql, objs);
	}
	
	/**根据sql取得urid列表*/
	private HashMap<Long, Integer> getUridListBySql(String pSql, Object[] pObjs) throws SQLException{
		HashMap<Long, Integer> list = new HashMap<Long, Integer>();
		List<Map<String, Object>> mapList = JDBCHelper.execQuery(partDbconn, pSql, pObjs);
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
	            Map<String, Object> eachMap = mapList.get(i);
	            list.put(Long.parseLong(eachMap.get("URID").toString()), Integer.parseInt(eachMap.get("ROWVERSION").toString()));
	        }
		}
		return list;
	}
	
	/**更新下载状态*/
	public int updateDownState(DownFileRecord pUpdateRd) throws SQLException, UnsupportedEncodingException{
		String tabName = getTableName();
		String sql = "update "+tabName+" set DOWNSTATE=?,DOWNINFO=?,DOWNTIME=?,LASTMODIFIEDON=?,ROWVERSION=ROWVERSION+1 where URID=?";
		Object[] objs;
		if("2".equals(pUpdateRd.downState)){
			objs = new Object[5];
		}else{
			sql+=" and ROWVERSION=?";
			objs = new Object[6];
			objs[5] = pUpdateRd.rowVersion;
		}
		
		objs[0] = pUpdateRd.downState;
		objs[1] = StringHelper.subStringByGBKByte(pUpdateRd.downInfo, 128);
		objs[2] = pUpdateRd.downTime;
		objs[3] = new Date();
		objs[4] = pUpdateRd.urid;
		
		return JDBCHelper.update(partDbconn, sql, objs);
	}
}
